<template>
  <view class="make-wallpaper-container">

    <view class="btn-container header-btn-container" style="margin: auto; justify-content: center;align-items: center;">
      <view class="layer-container">
        <view v-for="item in itemList" :key="item.id" class="layer-item">
          <view class="layer-content">
            <view class="layer-info" @click="showEdit(item)">
              <block v-if="item.layer_type === 'wallpaper_bg'">
                <view><u-icon name="photo" color="#622426" size="28"></u-icon></view>
                <view>底图</view>
              </block>
              <block v-if="item.layer_type === 'font'">
                <view><u-icon name="file-text" color="#622426" size="28"></u-icon></view>
                <view>文字</view>
              </block>
              <block v-if="item.layer_type === 'image'">
                <view><u-icon name="photo" color="#622426" size="28"></u-icon></view>
                <view>图片</view>
              </block>
            </view>

            <!-- 是否需要抠图 -->
            <view v-if="item.showEdit" class="edit-layer" :style="{
              width: item.layer_type === 'image' ? '480rpx' : '400rpx',
              left: item.layer_type === 'image' ? '-196rpx' : '-156rpx'
            }">
              <view v-if="item.layer_type === 'image'" class="edit-item" @click="item.matting = !item.matting">
                <view>
                  <image v-if="!item.matting" src="@/static/icon/ic_hand_del_n.png" class="edit-icon"></image>
                  <image v-else src="@/static/icon/ic_hand_del_s.png" class="edit-icon"></image>
                </view>
                <view>抠图</view>
              </view>
              <view class="edit-item" @click="item.zIndex = 999">
                <view>
                  <image src="@/static/icon/edit_layer_top.png" class="edit-icon"></image>
                </view>
                <view>置顶</view>
              </view>
              <view class="edit-item" @click="item.zIndex = item.zIndex + 1">
                <view>
                  <image src="@/static/icon/edit_layer_up.png" class="edit-icon"></image>
                </view>
                <view>上一层</view>
              </view>
              <view class="edit-item" @click="item.zIndex = item.zIndex - 1">
                <view>
                  <image src="@/static/icon/edit_layer_down.png" class="edit-icon"></image>
                </view>
                <view>下一层</view>
              </view>
              <view class="edit-item" @click="item.zIndex = 0">
                <view>
                  <image src="@/static/icon/edit_layer_bottom.png" class="edit-icon"></image>
                </view>
                <view>置底</view>
              </view>
            </view>
            <!-- 是否需要抠图 -->

          </view>
        </view>
      </view>
    </view>

    <!-- 操作区域 -->
    <view
      class="contentWarp"
      :style="{
        height: `${containerHeight}px`
      }">

      <view
        class="contentWarp-container"
        :style="{
          height: `${containerHeight}px`,
          width: `200px`,
          position: 'absolute'
        }">
        
        <view v-if="itemList.length <= 0" class="container" style="width: 200px;">
          <image class="bg" mode="widthFix" @click="uploadImage('bg')"
            src="https://qiniu-res.jintianwang.cc/20221212165919-d1deaa66c29f585ba8e1cdad4eebf29a.png"></image>
        </view>
        <!-- *************操作区域************* zIndex: item.active ? 100 : 1 -->
        <block v-for='(item, index) in itemList' :key="item.id">
          <!-- 圆心坐标 <text style='position:absolute;top:{{item.y}}px;left:{{item.x}}px;width:2px;height:2px;background-color:yellow;z-index:500'></text> -->

          <view v-if="item.layer_type === 'wallpaper_bg'" class="container"
            style="width: 200px;position: relative; pointer-events: none;" :style="{
              zIndex: item.zIndex
            }">
            <image class="bg" mode="widthFix" :src="item.image"></image>
          </view>

          <block v-else>
            <view class="touchWrap" :style='{
              transform: `scale(${item.scale})`,
              top: `${item.top}px`,
              left: `${item.left}px`,
              zIndex: item.zIndex
            }'>
              <view class="imgWrap" :class="{
                touchActive: item.active
              }" :style='{
    transform: `rotate(${item.angle}deg)`,
    // border: `${item.active ? 4 * item.oScale : 0}rpx #ff6d59 dashed`
  }'>
                <image :src='item.image' :data-id='item.id' :style='{
                  width: `${item.width}px`,
                  height: `${item.height}px`
                }' @touchstart.stop.prevent='WraptouchStart' @touchmove.stop.prevent='WraptouchMove'
                  @touchend.stop.prevent='WraptouchEnd'></image>
                <!-- <image
                  class="x icon-bg"
                  src="http://img-miniprogram-o.doutuimao.net/miniadmin/programconfig/xcximg/20220905/731c73dac78391794aabe42ec3977167.png"
                  :style='{
                    transform: `scale(${item.oScale})`,
                  }'
                  style="transform-origin: center;"
                  :data-id='item.id'
                  @tap='deleteLayer(index)'></image>
                <image
                  class="o icon-bg"
                  src="https://img-miniprogram-o.doutuimao.net/miniadmin/programconfig/xcximg/20220905/6167e679703427458e30157683912837.png"
                    :style='{
                    transform: `scale(${item.oScale})`,
                  }'
                  style="transform-origin: center; z-index: 9999;"
                  :data-id='item.id'
                  @touchstart.stop.prevent='oTouchStart'
                  @touchmove.stop.prevent='oTouchMove'
                  @touchend.stop.prevent='WraptouchEnd'>
                </image> -->
              </view>
            </view>
          </block>
        </block>
        <!-- **************操作区域************  -->

      </view>

      <block v-for='(item, index) in itemList' :key="item.id">
        <view v-if="item.layer_type !== 'wallpaper_bg'" class="touchWrap" :style='{
          transform: `scale(${item.scale})`,
          top: `${item.top}px`,
          left: `${item.left}px`,
          zIndex: 9998
        }'>
          <view class="imgWrap" :class="{
            touchActive: item.active
          }" :style='{
            transform: `rotate(${item.angle}deg)`,
            // border: `${item.active ? 4 * item.oScale : 0}rpx #ff6d59 dashed`
          }'>
            <view :data-id='item.id' :style='{
              width: `${item.width}px`,
              height: `${item.height}px`,
              opacity: 0
            }' @touchstart.stop.prevent='WraptouchStart' @touchmove.stop.prevent='WraptouchMove'
              @touchend.stop.prevent='WraptouchEnd'></view>
            <image class="x icon-bg"
              src="http://img-miniprogram-o.doutuimao.net/miniadmin/programconfig/xcximg/20220905/731c73dac78391794aabe42ec3977167.png"
              :style='{
                transform: `scale(${item.oScale})`,
              }' style="transform-origin: center; z-index: 9999;" :data-id='item.id' @tap='deleteLayer(index)'></image>
            <image class="o icon-bg"
              src="https://img-miniprogram-o.doutuimao.net/miniadmin/programconfig/xcximg/20220905/6167e679703427458e30157683912837.png"
              :style='{
                transform: `scale(${item.oScale})`,
              }' style="transform-origin: center; z-index: 9999;" :data-id='item.id'
              @touchstart.stop.prevent='oTouchStart' @touchmove.stop.prevent='oTouchMove'
              @touchend.stop.prevent='WraptouchEnd'>
            </image>
          </view>
        </view>
      </block>

    </view>

    <view class="btn-container">
      <view class="sava-image" @click="uploadImage('bg')">更换底图</view>
      <!-- <view class="sava-image" @click="uploadImage('bg_icon')">增加底图</view> -->
      <view class="sava-image" @click="addText">添加文字</view>
      <view class="sava-image" @click="uploadImage('image')">添加图片</view>
      <view class="sava-image save-template" @click="synthesis()">保存模板</view>
    </view>

    <!-- 文字操作区域 -->
    <view
      v-if="itemList.length > 0 && itemList[currentIndex] && itemList[currentIndex].layer_type === 'font' && itemList[currentIndex].active"
      class="edit-box">
      <view class="item">
        <input type="text" placeholder="请输入文字" :value="itemList[currentIndex].text" class="input" @blur="getText" />
        <view class="text-size">
          <view>{{ parseInt(itemList[currentIndex].width * itemList[currentIndex].scale) }} * {{
            parseInt(itemList[currentIndex].height * itemList[currentIndex].scale) }}</view>
          <view>X：{{ parseInt(itemList[currentIndex].left) }} Y: {{ parseInt(itemList[currentIndex].top) }}</view>
        </view>
      </view>
      <view class="item">
        <view class="gray font" @click="fontShow = true">
          <view class="text">{{ itemList[currentIndex].familyText }}</view>
          <image src="@/static/images/icon/down.png" class="down"></image>
        </view>
        <view class="gray font" @click="openColor">
          <view class="color" :style="{ backgroundColor: itemList[currentIndex].color }"></view>
          <view class="text">颜色</view>
          <image src="@/static/images/icon/down.png" class="down"></image>
        </view>
        <view class="gray" @click="changeFontDirection">
          <image src="@/static/images/icon/direction.png" mode="aspectFill" class="bold"></image>
          <view class="text" v-if="itemList[currentIndex].direction">纵向</view>
          <view class="text" v-else>横向</view>
        </view>
      </view>
    </view>

    <!-- 分类 -->
    <view class="category-list">
      <Title title="模板列表" :custom-style="{
        'marginBottom': '24rpx',
        'fontSize': '28rpx',
        'fontWeight': '700',
        'color': '#fff'
      }"></Title>
      <view class="type-container">
        <WallpaperArtworksList :artworks-list="artworksList" :is-batch="false" :is-mini="false"
          @handleArtworks="handleArtworks" />
      </view>
    </view>

    <!-- bug点：一定不要用if hidden 隐藏canvas会导致很多api调用bug -->
    <canvas class="maskCanvas" canvas-id="maskCanvas" :style='{
      width: `${canvasWidth}px`,
      height: `${canvasHeight}px`
    }'></canvas>

    <!-- 颜色选择器 -->
    <t-color-picker ref="colorPicker" :color="defaultColor" @confirm="selectColor" :scroll-top="scrollTop"
      :inputColor="true"></t-color-picker>

    <!-- 字体选择 -->
    <SelectFont mode="selector" v-model="fontShow" :range="allFontList" confirm-color="#56d39d"
      :default-selector="defaultFont" @confirm="fontConfirm"></SelectFont>

    <!-- 保存头像 -->
    <u-popup v-model="showCanvas" mode="center" width="600" border-radius="8">
      <view class="kefu-info">
        <scroll-view scroll-y="true" :scroll-into-view="rolldistance" :scroll-with-animation="true"
          style="max-height: 768rpx">
          <image :src="canvasTemImg" mode="widthFix" class="ewm"></image>
        </scroll-view>
        <input type="text" placeholder="请输入标题" v-model="wallpaperTitle" class="wallpaper-title" />
        <view class="ewm-text" @click="saveTemplate">提交模板</view>
      </view>
    </u-popup>


  </view>
</template>

<script>
import Title from '@/components/title/title';
import SelectFont from '@/components/selectFont/selectFont.vue';
import tColorPicker from '@/components/color/color.vue';
import config from '@/utils/config';
import { allFontList, textToImage } from '@/api/artworks';
import { createWallpaperTemplate, wallpaperTemplateList } from '@/api/applet';
import { dataURLtoFile, commonUploadFile } from '@/utils/index';
import WallpaperArtworksList from '@/components/artworksList/artworksList3.vue'; // 壁纸
const uuid = require("uuid");
let timer;
export default {
  components: {
    SelectFont,
    tColorPicker,
    Title,
    WallpaperArtworksList
  },
  data() {
    return {
      id: '', // 当前编辑的id
      wallpaperTitle: '', // 壁纸标题
      tool_id: '',
      business_id: '',
      containerHeight: 200, // 容器高度
      canvasTemImg: '',
      flag: false,
      rolldistance: '',
      showPreview: false,
      showCanvas: false,
      currentIndex: 0,
      canvasWidth: 0,
      canvasHeight: 0,
      wallpaper_bg: '', // 背景
      wallpaper_width: 0, // 背景宽度
      wallpaper_height: 0, // 背景高度
      hc: 1, // 高比例
      wc: 1, // 宽比例
      uploadUrl: config.baseApi + '/common/upload/templateImage',
      allFontList: [], // 字体列表
      currentFont: '', // 当前字体
      defaultFont: [0], // 默认
      fontShow: false, // 是否显示字体
      defaultColorStr: 'rgb(0,0,0)', // 默认颜色
      defaultColor: {
        r: 0,
        g: 0,
        b: 0,
        a: 1
      },
      scrollTop: 0,
      itemList: [],
      artworksList: [],
      l_x: 0, // 画布距离屏幕左边的位置
      t_y: 0, // 画布距离屏幕顶端的位置
      screenWidth: 0, // 设备宽度
      screenHeight: 0, // 设备高度
      proWidth: 200, // 画布的宽度
    }
  },

  onLoad(options) {
    this.getFontList();
    this.tool_id = options.tool_id;
    this.business_id = options.business_id;
    this.queryWallpaperTemplateList();
    const systemInfo = uni.getSystemInfoSync();
    this.screenWidth = systemInfo.screenWidth;
    this.screenHeight = systemInfo.screenHeight;
    this.l_x = (systemInfo.screenWidth - this.proWidth) / 2;
    this.t_y = uni.upx2px(168);
  },

  methods: {

    // 点击编辑模板
    async handleArtworks(itemData) {
      this.id = itemData.id;
      this.wallpaper_bg = itemData.wallpaper_bg;
      const imageArrt = await this.getImageInfo(itemData.wallpaper_bg);
      this.canvasWidth = imageArrt.width;
      this.canvasHeight = imageArrt.height;
      // 比例
      let wc = imageArrt.width / 200;
      this.wc = wc;
      let wc2 = 200 / imageArrt.width;
      let containerHeight = imageArrt.height * wc2;
      this.containerHeight = containerHeight;
      this.itemList = itemData.params;
      this.wallpaperTitle = itemData.title;
      //返回顶部
      uni.pageScrollTo({
        scrollTop: 0
      })
    },

    // 获取模板，根据分类
    queryWallpaperTemplateList() {
      wallpaperTemplateList({
        tool_id: this.tool_id,
        pageSize: 100,
        business_id: this.business_id
      }).then(result => {
        if (result && result.data && result.data.records) {
          this.artworksList = result.data.records;
        }
      })
    },

    // 保存模板
    saveTemplate() {

      const title = this.wallpaperTitle;
      if (!title) {
        uni.showToast({
          title: '请输入标题',
          icon: 'none'
        })
        return;
      }

      let file = dataURLtoFile(this.canvasTemImg, 'template');
      uni.showLoading({
        title: '保存中',
        mask: true
      })

      commonUploadFile(file.name, this.uploadUrl, { file }).then(result => {
        if (result) {
          let params = {
            id: this.id,
            tool_id: this.tool_id,
            params: this.itemList,
            cover_url: `${result.cover_path}?imageMogr2/auto-orient/thumbnail/456x/blur/1x0/quality/100`,
            thumbnail: `${result.cover_path}`,
            wallpaper_bg: this.wallpaper_bg,
            business_id: this.business_id,
            title,
          }
          // console.log(params)
          createWallpaperTemplate(params).then(result => {
            if (result && result.code === 200) {
              uni.hideLoading();
              uni.showToast({
                title: '保存成功',
                icon: 'none'
              })
              this.id = '';
              this.showCanvas = false;
              this.canvasTemImg = '';
              this.itemList = [];
              this.containerHeight = 200;
              this.queryWallpaperTemplateList();
            }
          })
        }
      })
    },

    // 显示置顶
    showEdit(itemData) {

      let itemList = this.itemList;
      itemList.forEach(item => {
        if (item.id !== itemData.id) {
          item.showEdit = false;
        }
      })
      itemData.showEdit = !itemData.showEdit;
    },

    // 确定选择颜色
    selectColor(e) {
      let color = 'rgb(' + e.rgba.r + ',' + e.rgba.g + ',' + e.rgba.b + ')';
      this.itemList[this.currentIndex].color = color;
      this.defaultColor = e.rgba;
      this.defaultColorStr = color;
      // this.changeTextArrt();
      this.textToImage(this.itemList[this.currentIndex]).then(result => {
        if (result && result.image) {
          this.itemList[this.currentIndex].image = result.image;
        }
      });
    },

    // 打开颜色选择器
    openColor() {
      this.$refs.colorPicker.open();
    },

    // 改变文字方向
    changeFontDirection() {
      this.itemList[this.currentIndex].direction = !this.itemList[this.currentIndex].direction;
      this.changeTextArrt();
    },

    //获取文字
    getText(e) {
      let val = e.target.value;
      if (val.length < 1) {
        uni.showToast({
          title: '不能为空',
          icon: 'none'
        })
      } else {
        this.itemList[this.currentIndex].text = val;
        // this.textToImage(this.dragList);
        this.changeFontSize();
      }
    },

    // 修改字体
    changeFontSize() {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        this.changeTextArrt();
        timer = null;
      }, 800);
    },

    // 删除图层
    deleteLayer(index) {
      this.itemList.splice(index, 1);
    },

    // 确定选择字体
    fontConfirm(index) {
      let i = index[0];
      this.defaultFont = index;
      this.fontShow = false;
      this.currentFont = this.allFontList[i];
      this.changeTextArrt();
    },

    // 改变字体图片
    changeTextArrt() {
      let text = {
        text: this.itemList[this.currentIndex].text,
        width: 0,
        height: 0,
        image: '',
        id: uuid.v1(),
        top: 0,
        left: 0,
        x: 0,
        y: 0,
        size: 160,
        scale: 1,
        oScale: 1,
        rotate: 1,
        active: false,
        font: this.currentFont.font_name,
        familyText: this.currentFont.title,
        layer_type: 'font',
        direction: this.itemList[this.currentIndex].direction,
        zIndex: 1,
        color: this.itemList[this.currentIndex].color,
        showEdit: this.itemList[this.currentIndex].showEdit,
        createPlatform: 'mp-kuaishou'
      }
      this.textToImage(text).then(result => {
        if (result && result.image) {
          text.image = result.image;
          text.width = result.width * 0.2;
          text.height = result.height * 0.2;
          text.x = result.width * 0.2 / 2;
          text.y = result.height * 0.2 / 2;
          this.itemList.splice(this.currentIndex, 1, text);
        }
      });
    },

    // 添加字体
    addText() {
      if (this.wallpaper_bg) {
        let color = this.defaultColorStr || 'rgb(0, 0, 0)';
        let text = {
          text: '默认',
          width: 0,
          height: 0,
          image: '',
          id: uuid.v1(),
          top: 0,
          left: 0,
          x: 0,
          y: 0,
          size: 160,
          scale: 1,
          oScale: 1,
          rotate: 1,
          active: false,
          font: this.currentFont.font_name,
          familyText: this.currentFont.title,
          layer_type: 'font',
          direction: true,
          zIndex: 1,
          color: this.defaultColorStr || 'rgb(0, 0, 0)',
          showEdit: false,
          createPlatform: 'mp-kuaishou'
        }

        this.textToImage(text, this.index).then(result => {
          if (result && result.image) {
            text.image = result.image;
            text.width = result.width * 0.2;
            text.height = result.height * 0.2;
            text.x = result.width * 0.2 / 2;
            text.y = result.height * 0.2 / 2;
            this.itemList.push(text);
          }
        })

      } else {
        uni.showToast({
          title: '请先上传底图',
          icon: 'none'
        })
      }
    },

    //制作字体图片
    async textToImage(item, index) {
      let that = this;
      uni.showLoading({
        title: '加载中...',
        mask: true,
        direction: 20 * 1000
      })
      return new Promise((resolve, reject) => {
        textToImage(item).then(result => {
          if (result.code == 200 && result.data) {
            const data = result.data;
            uni.hideLoading();
            resolve(data);
          } else {
            uni.showToast({
              icon: 'none',
              title: result.msg
            })
            reject();
          }
        }).catch(error => {
          reject();
        });
      })
    },

    //获取字体
    async getFontList() {
      let that = this;
      allFontList().then(result => {
        if (result.code == 200 && result.data && result.data.length > 0) {
          that.allFontList = result.data;
          this.currentFont = result.data[0];
        } else {
          uni.showToast({
            icon: 'none',
            title: '请添加字体文件在使用该功能'
          })
        }
      });
    },

    // 上传底图
    uploadImage(uploadType) {
      let that = this;
      let businessId = '';

      if (uploadType === 'image' && !this.wallpaper_bg) {
        uni.showToast({
          title: '请先上传底图',
          icon: 'none'
        })
        return;
      }

      // #ifdef MP
      businessId = config.id;
      // #endif
      // #ifdef H5
      businessId = uni.getStorageSync('businessId');
      // #endif
      uni.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        success: function (res) {
          let temp = res.tempFilePaths;
          uni.showLoading({
            title: '上传中',
            mask: true,
            direction: 20 * 1000
          })
          // console.log(temp[0])
          const uploadTask = uni.uploadFile({
            url: that.uploadUrl,
            filePath: temp[0],
            name: 'file',
            header: {
              businessId: businessId
            },
            success: async (imgRes) => {
              uni.hideLoading();
              let result = JSON.parse(imgRes.data)
              if (result.code == 200 && result.data) {
                const imageArrt = await that.getImageInfo(result.data.cover_path);
                // console.log(imageArrt);
                // 背景
                if (uploadType === 'bg') {
                  // 宽高
                  that.canvasWidth = imageArrt.width;
                  that.canvasHeight = imageArrt.height;
                  that.wallpaper_bg = result.data.cover_path;

                  // 比例
                  let wc = imageArrt.width / 200;
                  that.wc = wc;

                  let wc2 = 200 / imageArrt.width;
                  let containerHeight = imageArrt.height * wc2;

                  let image = {
                    text: '',
                    width: imageArrt.width,
                    height: imageArrt.height,
                    image: result.data.cover_path,
                    id: uuid.v1(),
                    top: 0,
                    left: 0,
                    x: 0,
                    y: 0,
                    scale: 1,
                    oScale: 1,
                    rotate: 1,
                    active: false,
                    layer_type: 'wallpaper_bg',
                    zIndex: 1,
                    showEdit: false
                  }
                  that.containerHeight = containerHeight;
                  that.itemList.splice(0, 1, image);
                } else if (uploadType === 'image') {
                  let rotateW = 200 / imageArrt.width;
                  let image = {
                    text: '',
                    width: 200,
                    height: imageArrt.height * rotateW,
                    image: result.data.cover_path,
                    id: uuid.v1(),
                    top: 0,
                    left: 0,
                    x: 200 / 2,
                    y: imageArrt.height * rotateW / 2,
                    size: 160,
                    scale: 1,
                    oScale: 1,
                    rotate: 1,
                    active: false,
                    layer_type: 'image',
                    zIndex: 1,
                    matting: false,
                    showEdit: false
                  }
                  that.itemList.push(image);
                } else if (uploadType === 'bg_icon') {
                  let rotateW = 200 / imageArrt.width;
                  let image = {
                    text: '',
                    width: 200,
                    height: imageArrt.height * rotateW,
                    image: result.data.cover_path,
                    id: uuid.v1(),
                    top: 0,
                    left: 0,
                    x: 200 / 2,
                    y: imageArrt.height * rotateW / 2,
                    size: 160,
                    scale: 1,
                    oScale: 1,
                    rotate: 1,
                    active: false,
                    layer_type: 'image',
                    zIndex: 1,
                    showEdit: false,
                    matting: false,
                  }
                  that.itemList.push(image);
                }
                uni.showToast({
                  icon: 'none',
                  title: result.msg
                })
              } else {
                uni.showToast({
                  icon: 'none',
                  title: '上传失败，请重试'
                })
              }
            },
            fail: function (e) {
              uni.hideLoading();
              console.log(e);
            }
          });
        },
        fail(e) {
          uni.hideLoading();
          console.log(e);
        }
      })
    },

    // 获取图片壁纸信息
    async getImageInfo(url) {
      return new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: url,
          success: (image) => {
            resolve({
              width: image.width,
              height: image.height,
            })
          }
        });
      })
    },

    // 开始
    WraptouchStart(e) {
      let items = this.itemList;
      // console.log(e)
      for (let i = 0; i < items.length; i++) {
        items[i].active = false;
        if (e.currentTarget.dataset.id == items[i].id) {
          this.currentIndex = i;
          items[this.currentIndex].active = true;
        }
      }

      items[this.currentIndex].lx = e.touches[0].clientX;
      items[this.currentIndex].ly = e.touches[0].clientY;
      this.itemList = items;
    },

    // 过程
    WraptouchMove(e) {
      if (this.flag) {
        this.flag = false;
        setTimeout(() => {
          this.flag = true;
        }, 200)
      }
      let items = this.itemList;
      items[this.currentIndex]._lx = e.touches[0].clientX;
      items[this.currentIndex]._ly = e.touches[0].clientY;

      items[this.currentIndex].left += items[this.currentIndex]._lx - items[this.currentIndex].lx;
      items[this.currentIndex].top += items[this.currentIndex]._ly - items[this.currentIndex].ly;
      items[this.currentIndex].x += items[this.currentIndex]._lx - items[this.currentIndex].lx;
      items[this.currentIndex].y += items[this.currentIndex]._ly - items[this.currentIndex].ly;

      items[this.currentIndex].lx = e.touches[0].clientX;
      items[this.currentIndex].ly = e.touches[0].clientY;
      this.itemList = items;
    },

    // 结束
    WraptouchEnd(e) {

    },

    // 放大开始
    oTouchStart(e) {
      //找到点击的那个图片对象，并记录
      let items = this.itemList;
      for (let i = 0; i < items.length; i++) {
        items[i].active = false;
        if (e.currentTarget.dataset.id == items[i].id) {
          this.currentIndex = i;
          items[this.currentIndex].active = true;
        }
      }

      //获取作为移动前角度的坐标
      const l_x = this.l_x;
      const t_y = this.t_y;
      // console.log(this.scrollTop)
      items[this.currentIndex].tx = e.touches[0].clientX - l_x;
      items[this.currentIndex].ty = e.touches[0].clientY - t_y;
      // console.log(items[this.currentIndex].tx, items[this.currentIndex].ty);
      //移动前的角度
      items[this.currentIndex].anglePre = this.countDeg(items[this.currentIndex].x, items[this.currentIndex].y, items[this.currentIndex].tx, items[this.currentIndex].ty)
      //获取图片半径
      items[this.currentIndex].r = this.getDistancs(items[this.currentIndex].x, items[this.currentIndex].y, items[this.currentIndex].left, items[this.currentIndex].top);

      // this.itemList = items;

      this.flag = false;
      setTimeout(() => {
        this.flag = true;
      }, 200)

      // console.log(items[this.currentIndex])

    },

    // 放大过程
    oTouchMove(e) {
      if (!this.flag) {
        return;
      }

      let items = this.itemList;
      const index = this.currentIndex;
      const l_x = this.l_x;
      const t_y = this.t_y;
      //记录移动后的位置
      items[index]._tx = e.touches[0].clientX - l_x;
      items[index]._ty = e.touches[0].clientY - t_y;
      //移动的点到圆心的距离
      // items[index].disPtoO = this.getDistancs(items[index].x, items[index].y, items[index]._tx, items[index]._ty - 10);
      items[index].disPtoO = this.getDistancs(items[index].x, items[index].y, items[index]._tx, items[index]._ty - 10);

      // console.log(items[index].disPtoO, items[index].r)

      items[index].scale = items[index].disPtoO / items[index].r;
      items[index].oScale = 1 / items[index].scale;

      //移动后位置的角度
      items[index].angleNext = this.countDeg(items[index].x, items[index].y, items[index]._tx, items[index]._ty)
      //角度差
      items[index].new_rotate = items[index].angleNext - items[index].anglePre;

      //叠加的角度差
      items[index].rotate += items[index].new_rotate;
      items[index].angle = items[index].rotate; //赋值

      //用过移动后的坐标赋值为移动前坐标
      items[index].tx = e.touches[0].clientX - l_x;
      items[index].ty = e.touches[0].clientY - t_y;
      items[index].anglePre = this.countDeg(items[index].x, items[index].y, items[index].tx, items[index].ty);

      this.itemList = items;
    },

    /*
    *参数1和2为图片圆心坐标
    *参数3和4为手点击的坐标
    *返回值为手点击的坐标到圆心的角度
    */
    countDeg: function (cx, cy, pointer_x, pointer_y) {
      let ox = pointer_x - cx;
      let oy = pointer_y - cy;
      let to = Math.abs(ox / oy);
      let angle = Math.atan(to) / (2 * Math.PI) * 360;
      // console.log("ox.oy:", ox, oy)
      if (ox < 0 && oy < 0) //相对在左上角，第四象限，js中坐标系是从左上角开始的，这里的象限是正常坐标系  
      {
        angle = -angle;
      } else if (ox <= 0 && oy >= 0) //左下角,3象限  
      {
        angle = -(180 - angle)
      } else if (ox > 0 && oy < 0) //右上角，1象限  
      {
        angle = angle;
      } else if (ox > 0 && oy > 0) //右下角，2象限  
      {
        angle = 180 - angle;
      }
      return angle;
    },

    // 获取半径
    getDistancs(cx, cy, pointer_x, pointer_y) {
      // console.log(cx, cy, pointer_x, pointer_y);
      let ox = pointer_x - cx;
      let oy = pointer_y - cy;
      return Math.sqrt(
        ox * ox + oy * oy
      );
    },

    // 合成
    openMask() {
      this.synthesis();
    },

    // 合成图片
    synthesis() {
      uni.showLoading({
        title: '生成中'
      })
      const maskCanvas = uni.createCanvasContext('maskCanvas');
      maskCanvas.save();
      maskCanvas.beginPath();
      maskCanvas.setFillStyle('#fff');
      maskCanvas.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
      maskCanvas.closePath();
      maskCanvas.stroke();

      // 元素列表
      let items = this.itemList;
      const sortList = items.sort(this.compare('zIndex'));
      items = sortList;
      // console.log(sortList);
      // let wallpaperZIndex = 0;
      // const wallpaperBgObject = items.filter(item => item.layer_type === 'wallpaper_bg')[0];
      // wallpaperZIndex = wallpaperBgObject.zIndex;
      // const wallpaperIsTop = items.some(item => {
      //   if (item.layer_type !== 'wallpaper_bg') {
      //     return wallpaperZIndex > item.zIndex;
      //   }
      // })

      // 背景
      // if (!wallpaperIsTop) {
      //   maskCanvas.drawImage(this.wallpaper_bg, 0, 0, this.canvasWidth, this.canvasHeight);
      // }

      /*
        加载图片
        num为canvas内背景图占canvas的百分比，若全背景num =1
        prop值为canvas内背景的宽度与可移动区域的宽度的比，如一致，则prop =1;
      */
      let num = 1;
      let prop = this.wc || 1;
      items.forEach((currentValue, index) => {
        currentValue.showEdit = false;
        if (currentValue.layer_type !== 'wallpaper_bg') {
          maskCanvas.save();
          maskCanvas.translate(this.canvasWidth * (1 - num) / 2, 0);
          maskCanvas.beginPath();
          maskCanvas.translate(currentValue.x * prop + 3, currentValue.y * prop + 3); //圆心坐标
          maskCanvas.rotate(currentValue.angle * Math.PI / 180);
          maskCanvas.translate(-(currentValue.width * currentValue.scale * prop / 2), -(currentValue.height * currentValue.scale * prop / 2))
          maskCanvas.drawImage(currentValue.image, 0, 0, currentValue.width * currentValue.scale * prop, currentValue.height * currentValue.scale * prop);
          maskCanvas.restore();
        } else if (currentValue.layer_type === 'wallpaper_bg') {
          maskCanvas.drawImage(this.wallpaper_bg, 0, 0, this.canvasWidth, this.canvasHeight);
        }
      })

      // 背景
      // if (wallpaperIsTop) {
      //   maskCanvas.drawImage(this.wallpaper_bg, 0, 0, this.canvasWidth, this.canvasHeight);
      // }

      // 生成图片
      maskCanvas.draw(false, (e) => {
        uni.canvasToTempFilePath({
          canvasId: 'maskCanvas',
          success: res => {
            uni.hideLoading();
            // console.log('draw success')
            // console.log(res.tempFilePath)
            this.canvasTemImg = res.tempFilePath;
            this.showCanvas = true;
          }
        }, this)
      })

    },

    // 根据zindex排序
    compare(property) {
      return function (a, b) {
        let value1 = a[property];
        let value2 = b[property];
        return value1 - value2;  //降序只需要  return value2- value1
      }
    }

  },

  onPageScroll(res) {
    this.scrollTop = res.scrollTop;
  }

}
</script>

<style lang=scss>
page {
  background-color: #000;
}

.header-btn-container {
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  z-index: 9999;
  background-color: #000;
}

.layer-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;

  .layer-info {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    flex-direction: column;
    background-color: #fdf1cc;
    padding: 12rpx 24rpx;
    border-radius: 8rpx;
    margin-right: 12rpx;
    color: #622426;

  }

  .layer-content {
    position: relative;
  }

  .edit-layer {
    padding: 12rpx 24rpx;
    background-color: #fdf1cc;
    border: 4rpx solid #622426;
    border-radius: 12rpx;
    position: absolute;
    left: -156rpx;
    right: 0;
    bottom: -140rpx;
    margin: auto;
    width: 480rpx;
    height: 130rpx;
    z-index: 999999;
    display: flex;
  }

  .edit-item {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-direction: column;
    background-color: #fff;
    width: 90rpx;
    font-size: 24rpx;
    color: #622426;
  }

  .edit-icon {
    width: 32rpx;
    height: 32rpx;
    margin-bottom: 6rpx;
  }
}

.btn-container {
  display: flex;
  padding: 32rpx;
  justify-content: space-between;

  .sava-image {
    width: 148rpx;
    height: 68rpx;
    line-height: 68rpx;
    color: #fff;
    text-align: center;
    background-color: #f8f8f8;
    border-radius: 16rpx;
    font-size: 24rpx;
    color: $uni-color-primary;
    border: 2rpx solid $uni-color-primary;
  }

  .save-template {
    background-color: $uni-color-primary;
    color: #fff;
  }
}

.make-wallpaper-container {
  padding-top: 168rpx;
  padding-bottom: 32rpx;
  width: 100%;
  overflow: hidden;
}

/**index.wxss**/
.bg {
  width: 100%;
  float: left;
}

.contentWarp {
  width: 200px;
  margin: auto;
  position: relative;
  border-radius: 16rpx;
  // overflow: hidden;
  /* background-color: #d1e3f1; */
}

.touchWrap {
  transform-origin: center;
  position: absolute;
  z-index: 100;
}

// .icon-bg{
//   background-color: #fff;
// }

.imgWrap {
  box-sizing: border-box;
  width: 100%;
  transform-origin: center;
  float: left;
  border: 5rpx transparent dashed;
}

.imgWrap image {
  float: left;
}

.touchActive .x {
  display: block;
}

.touchActive .o {
  display: block;
}

.x {
  position: absolute;
  top: -25rpx;
  left: -25rpx;
  z-index: 500;
  display: none;
  width: 44rpx;
  height: 44rpx;
  overflow: hidden;
  font-weight: bold;
  color: #d1e3f1;
}

.o {
  position: absolute;
  bottom: -25rpx;
  right: -25rpx;
  width: 44rpx;
  height: 44rpx;
  text-align: center;
  display: none;
  overflow: hidden;
  font-weight: bold;
  color: #d1e3f1;
}

.active {
  background-color: rgb(78, 114, 151);
}

.active view {
  border: none;
}

.touchActive {
  /* border: 4rpx #fff dashed; */
  z-index: 400;
  position: relative;
}

.touchActive::before {
  display: block;
  content: ' ';
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  border: 4rpx #ff6d59 dashed;
}

.fixed {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}


.canvasWrap {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 999;
  text-align: center;
}

.maskCanvas {
  position: absolute;
  left: -2000px;
  top: -5000px;
}

.btn {
  font-size: 30rpx;
  color: #81b7c4;
  border: 3rpx solid #81b7c4;
  background-color: #fff;
  line-height: 90rpx;
  width: 50%;
  margin-top: 20rpx;
  height: 90rpx;
}

.btnView view {
  padding-bottom: 20rpx;
}

.hand {
  position: absolute;
  left: 100rpx;
  right: 0;
  margin: auto;
  z-index: 100;
}

.getUserInfoBtn {
  position: initial;
  border: none;
  background-color: none;
}

.getUserInfoBtn::after {
  border: none;
}

.btn_view {
  display: flex;
  padding: 20rpx;
}

.btn_view button {
  width: 300rpx;
  font-size: 30rpx;
  color: #81b7c4;
  border: 3rpx solid #81b7c4;
  background-color: #fff;
  line-height: 90rpx;
}

.resImg {
  width: 75%;
  margin-top: 10px;
}

.edit-box {
  margin: 0 20rpx 30rpx 20rpx;
}

.edit-box .item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 20rpx 10rpx;
  position: relative;
}

.edit-box .item .text-size {
  position: absolute;
  right: 0;
  width: 160rpx;
  font-size: 22rpx;
  text-align: center;
  background-color: $uni-color-primary;
  height: 88rpx;
  border-radius: 10rpx;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}

.edit-box .item .btn {
  width: calc(50% - 10rpx);
  color: $uni-color-primary;
  background: #f3f7fb;
  border: 2rpx solid $uni-color-primary;
  line-height: 70rpx;
  font-size: 26rpx;
  height: 70rpx;
  text-align: center;
  border-radius: 10rpx;
}

.edit-box .item .input {
  width: 100%;
  background-color: #f5f5f5;
  font-size: 24rpx;
  height: 88rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  padding-right: 160rpx;
}

.wallpaper-title {
  background-color: #f5f5f5;
  font-size: 24rpx;
  height: 88rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  margin-top: 24rpx;
  border: 2rpx solid $uni-color-primary;
}

.edit-box .item .gray {
  height: 88rpx;
  flex: 1;
  display: flex;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
}

.edit-box .item .gray:nth-child(2) {
  margin: 0 24rpx;
}

.edit-box .item .gray .size {
  width: 40rpx;
  height: 35rpx;
  margin-right: 20rpx;
}

.edit-box .item .gray.font {
  justify-content: space-between;
  padding: 0 20rpx;
}

.edit-box .item .gray.font .down {
  width: 30rpx;
  height: 30rpx;
}

.edit-box .item .gray.font .color {
  margin-right: 20rpx;
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: $uni-color-primary;
}

.edit-box .item .gray.font .text {
  flex: 1;
}

.edit-box .item .gray .bold {
  width: 32rpx;
  height: 32rpx;
  margin-right: 10rpx;
}

.kefu-info {
  font-size: 0;
  padding: 24rpx 24rpx 0;
}

.ewm {
  width: 100%;
}

.ewm-text {
  background-color: $uni-color-primary;
  color: #fff;
  width: 260rpx;
  text-align: center;
  border-radius: 40rpx;
  padding: 20rpx 0;
  margin: 20rpx auto;
  font-size: 28rpx;
}

.category-list {
  box-shadow: 0 0 20rpx rgba(0, 0, 0, .1);
  padding: 32rpx;
  border-radius: 10rpx;
}

.contentWarp-container{
  overflow: hidden;
}
</style>
